package middleware

import (
	"os"

	"daxin.my/test-netserver/api"
)

const (
	// 环境变量
	MysqlInit         = "MYSQL_CLIENT_INIT"
	PostgresInit      = "POSTGRES_CLIENT_INIT"
	RedisInit         = "REDIS_CLIENT_INIT"
	KafkaProducerInit = "KAFKA_PRODUCER_INIT"
	KafkaConsumerInit = "KAFKA_CONSUMER_INIT"
	KafkaBrokerList   = "KAFKA_BROKER_LIST"

	// CLIENT KEY
	CLIENT_MYSQL    = "mysql"
	CLIENT_POSTGRES = "postgres"
	CLIENT_REDIS    = "redis"
	CLIENT_KAFKA    = "kafka"
)

func InitMiddlewares() {
	if os.Getenv(MysqlInit) == "true" {
		api.MiddlewareClients[CLIENT_MYSQL] = NewMysqlClient()
	}

	if os.Getenv(PostgresInit) == "true" {
		api.MiddlewareClients[CLIENT_POSTGRES] = NewPostgresClient()
	}

	if os.Getenv(RedisInit) == "true" {
		api.MiddlewareClients[CLIENT_REDIS] = NewRedisClient()
	}

	if os.Getenv(KafkaProducerInit) == "true" {
		api.MiddlewareClients[CLIENT_KAFKA] = NewKafkaProducer(os.Getenv(KafkaBrokerList))
	}

	if os.Getenv(KafkaConsumerInit) == "true" {
		KafkaConsumer := NewKafkaConsumer(os.Getenv(KafkaBrokerList))
		go KafkaConsumer.Consume()
	}
}

func VisitMiddleWare(key string) {
	client := api.MiddlewareClients[key]
	if client == nil {
		return
	}
	client.Visit()
}
